package com.ecco.persistent;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class AccObColAgentBean implements AccObColAgentLocal, AccObColAgentRemote {
	
	//	 property constants
	public static final String ACC_ID = "acc_id";
	public static final String OB_ID = "ob_id";
	public static final String COL_ID = "col_id";
		
	@PersistenceContext(unitName="eccodb") private EntityManager entityManager;
	
	public void save(AccObCol persistentInstance) {
		entityManager.persist(persistentInstance);
	}
	
	public void delete(AccObCol persistentInstance) {
		entityManager.remove(persistentInstance);
	}
	
	public AccObCol update(AccObCol detachedInstance) {
		return entityManager.merge(detachedInstance);
	}
	

	public AccObCol findAOCById(Integer aoc_id) {
		AccObCol accObCol = entityManager.find(AccObCol.class, aoc_id);
		return accObCol;
	}
	
	@SuppressWarnings("unchecked")
	public List<AccObCol> findAll() {
		String queryString = "SELECT model FROM AccObCol model";
		return entityManager.createQuery(queryString).getResultList();
	}
	
	public void addAccObCol(Integer acc_id, Integer ob_id, Integer col_id, String comment) {
		AccObCol accObCol = new AccObCol();
		Account account = new Account(acc_id);
		accObCol.setAccount(account);
		Objects objects = new Objects(ob_id);
		accObCol.setObjects(objects);
		Colour colour = new Colour(col_id);
		accObCol.setColour(colour);
		accObCol.setComment(comment);
		entityManager.persist(accObCol);
	}
	
	public void updateAccObCol(Integer aoc_id, Integer acc_id, Integer ob_id, Integer col_id, String comment) {
		AccObCol accObCol = entityManager.find(AccObCol.class, aoc_id);
		if (accObCol!=null) {
			Account account = new Account(acc_id);
			accObCol.setAccount(account);
			Objects objects = new Objects(ob_id);
			accObCol.setObjects(objects);
			Colour colour = new Colour(col_id);
			accObCol.setColour(colour);
			accObCol.setComment(comment);
			entityManager.merge(accObCol);
		}
	}
		
	public void removeAOCById(Integer aoc_id) {
		AccObCol accObCol = entityManager.find(AccObCol.class, aoc_id);
		if (accObCol!=null) entityManager.remove(accObCol);
	}
	
	@SuppressWarnings("unchecked")
	public Boolean checkAOCByAcc_Ob_Col(Account account, Objects objects, Colour colour) {
		String queryString = "SELECT model FROM AccObCol model WHERE model.account = :accValue AND model.objects = :obValue AND model.colour = :colValue";
		Query queryCheckAccObCol = entityManager.createQuery(queryString);
		queryCheckAccObCol.setParameter("accValue", account);
		queryCheckAccObCol.setParameter("obValue", objects);
		queryCheckAccObCol.setParameter("colValue", colour);
		List checkAOCRecordsResult = queryCheckAccObCol.getResultList();
		if (checkAOCRecordsResult.size()== 0){return false;}
		return true;
	}
	
}
